const request = require('request');
const { execSQL } = require('../db/mysql');
const { WX_CONFIG } = require('../configs/wxconfig');

// code转openid
const getOpenid = (code) => {
    return new Promise((resolve, reject) => {
        let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${WX_CONFIG.appid}&secret=${WX_CONFIG.appsecret}&js_code=${code}&grant_type=authorization_code`;
        request(url, (err, res, body) => {
            if (err) {
                reject(err);
                return;
            }
            // 解析body
            const { openid } = JSON.parse(body);
            resolve(openid);
        });
    });
}

// 创建用户
const createUser = async (code) => {
    const openid = await getOpenid(code);
    // 判断用户是否存在
    const sql = `select * from USER where openid='${openid}'`;
    const result = await execSQL(sql);
    if (result.length > 0) {
        return result[0].id;
    }
    // 创建用户
    const sql_2 = `insert into USER (openid,registration_time) values ('${openid}', ${Date.now()})`;
    const insertedResult = await execSQL(sql_2);
    return await insertedResult.insertId;
}

// 获取用户信息
const getUserInfo = async (code) => {
    const openid = await getOpenid(code);
    const sql = `select * from USER where openid='${openid}'`;
    const result = await execSQL(sql);
    return await result[0];
}

// 添加用户书籍
const addUserBook = async (userid, book_id) => {
    const sql = `insert into USER_BOOK (openid, book_id) values ('${userid}', ${book_id})`;
    const insertedResult = await execSQL(sql);
    return insertedResult.insertId;
}

// 获取用户书籍
const getUserBook = (userid) => {
    const sql = `select * from USER_BOOK where user_id='${userid}'`;
    return execSQL(sql);
}

// 添加用户单词
const addUserVOC = (body) => {
    let voc_id = body.voc_id;
    let user_id = body.user_id;
    let level = body.level;
    let next_review_time = body.next_review_time;
    let sql = `insert into USER_VOC (voc_id, user_id, level, next_review_time) values ('${voc_id}', '${user_id}', '${level}', '${next_review_time}')`;
    return execSQL(sql);
}

// 获取用户单词
const getUserVOC = (userid, level) => {
    let sql = `select * from USER_VOC where user_id='${userid}' and level='${level}'`;
    return execSQL(sql);
}

// 更新用户单词
const updateUserVOC = async (body) => {
    let id = body.id;
    let level = body.level;
    let next_review_time = body.next_review_time;
    let sql = `update USER_VOC set level='${level}', next_review_time='${next_review_time}' where id='${id}'`;
    const result = await execSQL(sql);
    if (result.affectedRows > 0) {
        return true;
    }
    return false;
}


module.exports = {
    createUser,
    getUserInfo,
    addUserBook,
    getUserBook,
    addUserVOC,
    getUserVOC,
    updateUserVOC,
}